package com.soft.line.filter;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class GlobalApplicationContextHolder implements ApplicationContextAware {

    private static ApplicationContext context;

    /**
     * <p>because the ApplicationContextAware interface is implemented, </p>
     * <p>when it is configured as bean, it will automatically injecting ApplicationContext.</p>
     */
    @Override
    public void setApplicationContext(final ApplicationContext applicationContext) {
        setAppContext(applicationContext);
    }

    /**
     * provide a static method for setting up ApplicationContext.
     * 
     * @param applicationContext
     */
    public static void setAppContext(final ApplicationContext applicationContext) {
        context = applicationContext;
    }

    /**
     * static method to obtain ApplicationContext
     * 
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return context;
    }

    /**
     * get bean based on the bean name.
     * 
     * @param name
     *
     * @return
     */
    public static Object getBean(final String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * get bean (generic) according to Class.
     * 
     * @param clazz
     * @return
     */
    public static <T> T getBean(final Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * get all the bean to implement an interface based on Class.
     * 
     * @param clazz
     * @return
     */
    public static <T> Map<String, T> getBeansOfType(final Class<T> clazz) {
        return getApplicationContext().getBeansOfType(clazz);
    }
}
